/**
 * Written By: Nicholas Hillier, Jan 15, 2009
 * Moves the playhead on a MovieClip from frame 1 to frame 2 on rollOver 
 * and back to frame 1 on rollout, 
 * 
 * uses a callback function on MouseClick that was passed in on creation
 * Button can be both enabled and diabled
 */
package com.cbc.ourgame.slideshowmaker.components.ui
{
	import caurina.transitions.Tweener;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	public class FrameButton
	{
		private var _view:MovieClip;
		private var _callBack:Function;
		private var _disableState:Bitmap;
		
		public function get view():MovieClip { return _view; }
		
		/**
		 * 
		 * @param view - the asset movieclip used as the button, has exactly 2 frame, RollOut and RollOver
		 * @param callback - Function to call when button is clicked, returns MouseEvent
		 * 
		 */
		public function FrameButton(view:MovieClip)
		{
			_view = view;
			_view.stop();
			_view.mouseChildren = false;
			enable();
			
			_disableState = new Bitmap(new BitmapData(_view.width, _view.height, true, 0));
			_disableState.bitmapData.draw(_view);
			_disableState.alpha = 0.7;
			Tweener.addTween(_disableState, {_color:0x676767, time:0})
		}
		
		public function addCallback(callback:Function):void
		{
			_callBack = callback;
		}
		
		public function enable():void
		{
			_view.alpha = 1;
			try{_view.removeChild(_disableState)}catch(e:Error){}
			_view.buttonMode = true;
			_view.addEventListener(MouseEvent.ROLL_OUT, onMouseAction);
			_view.addEventListener(MouseEvent.ROLL_OVER, onMouseAction);
			_view.addEventListener(MouseEvent.CLICK, onMouseAction);
		}
		
		public function disable(showAlpha:Boolean = false, showGrey:Boolean = false):void
		{
			if(showAlpha) _view.alpha = 0.5;
			if(showGrey) _view.addChild(_disableState);
			_view.buttonMode = false;
			_view.removeEventListener(MouseEvent.ROLL_OUT, onMouseAction);
			_view.removeEventListener(MouseEvent.ROLL_OVER, onMouseAction);
			_view.removeEventListener(MouseEvent.CLICK, onMouseAction);
		}
		
		private function onMouseAction(e:MouseEvent):void
		{
			switch(e.type)
			{
				case MouseEvent.ROLL_OUT: _view.gotoAndStop(1); break;
				case MouseEvent.ROLL_OVER: _view.gotoAndStop(2); break;
				case MouseEvent.CLICK: if(_callBack != null)_callBack(e); break;
			}	
		}

	}
}